package com.example.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.example.gateway.config.GatewayProperties;
import com.example.gateway.config.GatewayProperties.MultiTenant;
import com.example.gateway.exception.InvalidTenantException;
import com.example.starter.constant.WebConstant;
import com.example.starter.util.AntPathUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * @author 王令
 * @since 2022/10/16 11:31
 */
//@Order(Ordered.TENANT_CHECK)
@RequiredArgsConstructor
//@Configuration
public class TenantCheckGlobalFilter implements GlobalFilter {

    /**
     * 临时方案
     */
    private static final Set<String> TENANT_ID_LIST = CollUtil.newHashSet("e_cloud", "wfu");

    private final GatewayProperties properties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();
        MultiTenant multiTenant = properties.getMultiTenant();
        // 放行
        if (AntPathUtil.matches(multiTenant.getPermitUrls(), uri)) {
            return chain.filter(exchange);
        }
        String tenantId = request.getHeaders().getFirst(WebConstant.TENANT);
        if (StrUtil.isBlank(tenantId) || !TENANT_ID_LIST.contains(tenantId)) {
            throw new InvalidTenantException("不是合法租户");
        }
        return chain.filter(exchange);
    }

}
